//
//  NSObject+Propertys.swift
//  Persistance
//
//  Created by apple on 2018/10/29.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation

extension NSObject {
    
    func getPropertyNames() -> [String] {
        
        var outCount:UInt32
        
        outCount = 0
        
        
        let propers:UnsafeMutablePointer<objc_property_t>! =  class_copyPropertyList(self.classForCoder, &outCount)
        
        
        let count:Int = Int(outCount);
        
        print(outCount)
        
        var dics:[String] = [String]()
        for i in 0...(count-1) {
            
            let aPro: objc_property_t = propers[i]
            
            let proName:String! = String(utf8String: property_getName(aPro))
            dics.append(proName)
//            print(proName)
            
        }
        
        return dics
    }

    
    var toDic: [AnyHashable: Any] {
        
        var dic: [AnyHashable: Any] = [AnyHashable: Any]()
        
        var outCount: UInt32 = 0
        
        let list:UnsafeMutablePointer <objc_property_t>! = class_copyPropertyList(self.classForCoder, &outCount)
        let count:Int = Int(outCount);
        
        for i in 0...(count - 1) {
            
            let aPro: objc_property_t = list[i]
            
            let proName:String! = String(utf8String: property_getName(aPro))
            
            let value: AnyObject = self.value(forKey: proName) as AnyObject
            
            dic.updateValue(value as Any, forKey: proName)
            
        }
        return dic
    }
}
